#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPushButton>
#include <QDebug>
#include <cmath>
#include <QLineEdit>
#include <QKeyEvent>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , currentValue(0.0)
    , waitingValue(0.0)
    , waitingOperator("")
    , waitingForOperand(true)
{
    ui->setupUi(this);

    setFocusPolicy(Qt::StrongFocus);
    setFocus();

    for (int i = 0; i <= 9; ++i)
    {
        QString buttonName = QString("pushButton_%1").arg(i);
        QPushButton *button = findChild<QPushButton*>(buttonName);
        if (button)
        {
            connect(button, &QPushButton::clicked, this, &MainWindow::digitPressed);
        }
    }

    // 连接二元运算符按钮
    connect(findChild<QPushButton*>("pushButton_plus"), &QPushButton::clicked, this, &MainWindow::binaryOperatorPressed);
    connect(findChild<QPushButton*>("pushButton_minus"), &QPushButton::clicked, this, &MainWindow::binaryOperatorPressed);
    connect(findChild<QPushButton*>("pushButton_multiply"), &QPushButton::clicked, this, &MainWindow::binaryOperatorPressed);
    connect(findChild<QPushButton*>("pushButton_divide"), &QPushButton::clicked, this, &MainWindow::binaryOperatorPressed);

    // 连接一元运算符按钮
    connect(findChild<QPushButton*>("pushButton_sqrt"), &QPushButton::clicked, this, &MainWindow::unaryOperatorPressed);
    connect(findChild<QPushButton*>("pushButton_square"), &QPushButton::clicked, this, &MainWindow::unaryOperatorPressed);
    connect(findChild<QPushButton*>("pushButton_reciprocal"), &QPushButton::clicked, this, &MainWindow::unaryOperatorPressed);

    // 连接其他功能按钮
    connect(findChild<QPushButton*>("pushButton_equals"), &QPushButton::clicked, this, &MainWindow::equalsPressed);
    connect(findChild<QPushButton*>("pushButton_clear"), &QPushButton::clicked, this, &MainWindow::clearPressed);
    connect(findChild<QPushButton*>("pushButton_clearEntry"), &QPushButton::clicked, this, &MainWindow::clearEntryPressed);
    connect(findChild<QPushButton*>("pushButton_sign"), &QPushButton::clicked, this, &MainWindow::changeSignPressed);
    connect(findChild<QPushButton*>("pushButton_point"), &QPushButton::clicked, this, &MainWindow::pointPressed);
    connect(findChild<QPushButton*>("pushButton_percent"), &QPushButton::clicked, this, &MainWindow::percentPressed);
    connect(findChild<QPushButton*>("pushButton_delete"), &QPushButton::clicked, this, &MainWindow::deletePressed);

    ui->lineEdit->setText("0");
    ui->lineEdit->setReadOnly(true);
    ui->lineEdit->setAlignment(Qt::AlignRight);
}

MainWindow::~MainWindow()
{
    delete ui;
}

// 键盘事件处理
void MainWindow::keyPressEvent(QKeyEvent *event)
{
    int key = event->key();

    switch (key)
    {
    // 数字键 0-9
    case Qt::Key_0:
        simulateButtonClick("pushButton_0");
        break;
    case Qt::Key_1:
        simulateButtonClick("pushButton_1");
        break;
    case Qt::Key_2:
        simulateButtonClick("pushButton_2");
        break;
    case Qt::Key_3:
        simulateButtonClick("pushButton_3");
        break;
    case Qt::Key_4:
        simulateButtonClick("pushButton_4");
        break;
    case Qt::Key_5:
        simulateButtonClick("pushButton_5");
        break;
    case Qt::Key_6:
        simulateButtonClick("pushButton_6");
        break;
    case Qt::Key_7:
        simulateButtonClick("pushButton_7");
        break;
    case Qt::Key_8:
        simulateButtonClick("pushButton_8");
        break;
    case Qt::Key_9:
        simulateButtonClick("pushButton_9");
        break;

    // 运算符
    case Qt::Key_Plus:
        simulateButtonClick("pushButton_plus");
        break;
    case Qt::Key_Minus:
        simulateButtonClick("pushButton_minus");
        break;
    case Qt::Key_Asterisk:
    case Qt::Key_multiply:
        simulateButtonClick("pushButton_multiply");
        break;
    case Qt::Key_Slash:
    case Qt::Key_division:
        simulateButtonClick("pushButton_divide");
        break;

    // 等号和回车
    case Qt::Key_Equal:
    case Qt::Key_Return:
    case Qt::Key_Enter:
        simulateButtonClick("pushButton_equals");
        break;

    // 小数点
    case Qt::Key_Period:
    case Qt::Key_Comma:
        simulateButtonClick("pushButton_point");
        break;

    // 清除功能
    case Qt::Key_Escape:
        simulateButtonClick("pushButton_clear");
        break;
    case Qt::Key_Delete:
        simulateButtonClick("pushButton_clearEntry");
        break;
    case Qt::Key_Backspace:
        simulateButtonClick("pushButton_delete");
        break;

    // 百分比
    case Qt::Key_Percent:
        simulateButtonClick("pushButton_percent");
        break;

    // 正负号切换
    case Qt::Key_ParenLeft:  // 通常用Shift+9表示正负号
    case Qt::Key_AsciiTilde: // ~键
        simulateButtonClick("pushButton_sign");
        break;

    default:
        // 其他按键交给父类处理
        QMainWindow::keyPressEvent(event);
        return;
    }

    // 接受按键事件
    event->accept();
}

// 模拟按钮点击的辅助函数
void MainWindow::simulateButtonClick(const QString& buttonName)
{
    QPushButton *button = findChild<QPushButton*>(buttonName);
    if (button && button->isEnabled())
    {
        // 模拟按钮点击效果
        button->animateClick();
    }
}

void MainWindow::digitPressed()
{
    QPushButton *button = qobject_cast<QPushButton*>(sender());
    if (!button) return;

    QString digitValue = button->text();
    QString currentText = ui->lineEdit->text();

    if (currentText == "0" || currentText == "Error" || waitingForOperand)
    {
        ui->lineEdit->setText(digitValue);
        waitingForOperand = false;
    } else
    {
        ui->lineEdit->setText(currentText + digitValue);
    }
}

void MainWindow::binaryOperatorPressed()
{
    QPushButton *button = qobject_cast<QPushButton*>(sender());
    if (!button) return;

    QString clickedOperator = button->text();
    currentValue = ui->lineEdit->text().toDouble();

    if (!waitingOperator.isEmpty())
    {
        equalsPressed();
    }

    waitingOperator = clickedOperator;
    waitingValue = currentValue;
    waitingForOperand = true;
}

void MainWindow::unaryOperatorPressed()
{
    QPushButton *button = qobject_cast<QPushButton*>(sender());
    if (!button) return;

    QString clickedOperator = button->text();
    double operand = ui->lineEdit->text().toDouble();
    double result = 0.0;

    if (clickedOperator == "√")
    {
        if (operand < 0) {
            ui->lineEdit->setText("Error");
            return;
        }
        result = std::sqrt(operand);
    }
    else if (clickedOperator == "x²")
    {
        result = operand * operand;
    }
    else if (clickedOperator == "1/x")
    {
        if (operand == 0)
        {
            ui->lineEdit->setText("Error");
            return;
        }
        result = 1.0 / operand;
    }

    ui->lineEdit->setText(QString::number(result));
    waitingForOperand = true;
}

void MainWindow::equalsPressed()
{
    double operand = ui->lineEdit->text().toDouble();
    double result = 0.0;

    if (waitingOperator == "+")
    {
        result = waitingValue + operand;
    }
    else if (waitingOperator == "-")
    {
        result = waitingValue - operand;
    }
    else if (waitingOperator == "×")
    {
        result = waitingValue * operand;
    }
    else if (waitingOperator == "÷")
    {
        if (operand == 0)
        {
            ui->lineEdit->setText("Error");
            waitingOperator = "";
            waitingForOperand = true;
            return;
        }
        result = waitingValue / operand;
    }
    else
    {
        result = operand;
    }

    ui->lineEdit->setText(QString::number(result));
    waitingOperator = "";
    waitingForOperand = true;
}

void MainWindow::clearPressed()
{
    ui->lineEdit->setText("0");
    currentValue = 0.0;
    waitingValue = 0.0;
    waitingOperator = "";
    waitingForOperand = true;
}

void MainWindow::clearEntryPressed()
{
    ui->lineEdit->setText("0");
    waitingForOperand = true;
}

void MainWindow::changeSignPressed()
{
    double value = ui->lineEdit->text().toDouble();
    ui->lineEdit->setText(QString::number(-value));
}

void MainWindow::pointPressed()
{
    QString currentText = ui->lineEdit->text();

    if (waitingForOperand || currentText == "Error")
    {
        ui->lineEdit->setText("0.");
        waitingForOperand = false;
    }
    else if (!currentText.contains('.'))
    {
        ui->lineEdit->setText(currentText + ".");
    }
}

void MainWindow::percentPressed()
{
    double value = ui->lineEdit->text().toDouble();
    ui->lineEdit->setText(QString::number(value / 100.0));
    waitingForOperand = true;
}

void MainWindow::deletePressed()
{
    QString currentText = ui->lineEdit->text();

    if (currentText == "Error" || currentText.length() == 1)
    {
        ui->lineEdit->setText("0");
        waitingForOperand = true;
    }
    else if (currentText.length() > 1)
    {
        currentText.chop(1);
        ui->lineEdit->setText(currentText);
    }
}
